#include "stdafx.h"
#include "Scene.h"

#include "Camera.h"
#include "ModelNode.h"
#include "Renderer.h"
#include "AppData.h"

using namespace mscene;

Scene::Scene()
{
	mActiveCamera = new Camera;
	onResize();
}

Scene::~Scene()
{
	delete mActiveCamera;
	for(size_t i=0 ; i<mModelNodes.size() ; ++i)
		delete mModelNodes[i];
}

void Scene::setActiveCamera(Camera * camera)
{
	assert(camera != NULL);
	mActiveCamera = camera;
}

void Scene::addModelNode(ModelNode * node)
{
	mModelNodes.push_back(node);
}

void Scene::update(float dt)
{
	if(GetAsyncKeyState('A') & 0x8000)	mActiveCamera->strafe(-20.0f*dt);
	if(GetAsyncKeyState('D') & 0x8000)	mActiveCamera->strafe(+20.0f*dt);
	if(GetAsyncKeyState('W') & 0x8000)	mActiveCamera->walk(+20.0f*dt);
	if(GetAsyncKeyState('S') & 0x8000)	mActiveCamera->walk(-20.0f*dt);

	if(GetAsyncKeyState('Q') & 0x8000)	mActiveCamera->rotateY(-2.0f*dt);
	if(GetAsyncKeyState('E') & 0x8000)	mActiveCamera->rotateY(+2.0f*dt);
	if(GetAsyncKeyState('R') & 0x8000)  mActiveCamera->pitch(-2.0f*dt);
	if(GetAsyncKeyState('F') & 0x8000)	mActiveCamera->pitch(+2.0f*dt);

	mActiveCamera->rebuildView();
}

void Scene::draw()
{
	mgfx::gRenderer->setView(mActiveCamera->view());
	mgfx::gRenderer->setEyePos(mActiveCamera->position());

	for(size_t i=0 ; i<mModelNodes.size() ; ++i)
		mModelNodes[i]->sendToRenderer();
}

void Scene::onResize()
{
	float aspect = (float)AppData::Instance.ScreenWidth / (float)AppData::Instance.ScreenHeight;
	mActiveCamera->setLens(0.25f * PI, aspect, 0.5f, 1000.0f);
	mgfx::gRenderer->setProj(mActiveCamera->proj());
}